package eu.fsiebert.polytech.db.mediatheque.jsf;

import eu.fsiebert.polytech.db.mediatheque.entity.Adherent;
import eu.fsiebert.polytech.db.mediatheque.jsf.util.JsfUtil;
import eu.fsiebert.polytech.db.mediatheque.jsf.util.PaginationHelper;
import eu.fsiebert.polytech.db.mediatheque.session.AdherentFacade;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@ManagedBean(name = "adherentController")
@SessionScoped
public class AdherentController implements Serializable {

    private Adherent current;
    private DataModel items = null;
    @EJB
    private eu.fsiebert.polytech.db.mediatheque.session.AdherentFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    private MessageDigest algo;

    public AdherentController() {
        try {
            algo = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public Adherent getSelected() {
        if (current == null) {
            current = new Adherent();
            selectedItemIndex = -1;
        }
        return current;
    }

    private AdherentFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Adherent) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Adherent();
        current.setDateAdhesion(new Date());
        current.setPassword(getFacade().getRandomPassword());
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        String password = current.getPassword();
        try {
            current.setPassword(hash(password));
            getFacade().create(current);
            sendWelcomEmail(current.getLogin(), password);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AdherentCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            System.err.println(e.getMessage());
            current.setPassword(password);
            return null;
        }
    }

    private String hash(String str) {
        byte[] toHash = str.getBytes();
        byte[] digest = null;
        StringBuilder hashString = new StringBuilder();

        algo.reset();
        algo.update(toHash);
        digest = algo.digest();

        for (int i = 0; i < digest.length; i++) {
            String hex = Integer.toHexString(digest[i]);
            if (hex.length() == 1) {
                hashString.append('0');
                hashString.append(hex.charAt(hex.length() - 1));
            } else {
                hashString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashString.toString();
    }

    private void sendWelcomEmail(String login, String password) {
        String emailFrom = "Projet Médiathèque <no-reply@fsiebert.eu>";
        String emailTo = login;

        String subject = "Inscription à la médiathèque";
        String messageText = "Bonjour,\n\nVous êtes désormais inscrit à la médiathèque, vous pouvez consulter notre catalogue en vous onnectant sur notre site internet.\nNom d'utilisateur : " + login + "\nMot de passe : " + password + "\n\nA bientôt sur notre site.";

        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", "smtp.free.fr");

            javax.mail.Session maSession = javax.mail.Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(maSession);

            message.setFrom(new InternetAddress(emailFrom));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
            message.setSubject(subject);
            message.setText(messageText);

            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public String prepareEdit() {
        current = (Adherent) getItems().getRowData();
        current.setPassword(null);
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            if(current.getPassword() == null) {
                Adherent tmp = getFacade().find(new Adherent(current.getNoCarte()));
                System.err.println(tmp.getPassword());
                current.setPassword(tmp.getPassword());
            } else {
                current.setPassword(hash(current.getPassword()));
            }
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AdherentUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Adherent) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AdherentDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Adherent.class)
    public static class AdherentControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            AdherentController controller = (AdherentController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "adherentController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Adherent) {
                Adherent o = (Adherent) object;
                return getStringKey(o.getNoCarte());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AdherentController.class.getName());
            }
        }
    }
}
